import React, { createRef, useEffect, useState } from 'react';
import { connect, Dispatch, history } from 'umi';
import { ConnectState, IResponse } from '@/models/connect';
import { Breadcrumb, Button, Form, Input, message, Modal, Select, Table, TreeSelect } from 'antd';
import styles from './style.less';
import { IDashboardOperation, ITreeNode } from '@/pages/data';
import {
  DeleteOutlined,
  EditOutlined,
  FolderAddOutlined,
  FolderFilled,
  FundFilled,
  FundOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { ICurrentUser } from '@/models/user';

const classnames = require('classnames');

const { Option } = Select;

interface PanelProps {
  dispatch: Dispatch;
  dashboardOperations: IDashboardOperation[]
  currentUser: ICurrentUser
  projectId:number
}

const Board: React.FC<PanelProps> = (props) => {
  const { dashboardOperations, dispatch, currentUser,projectId } = props;
  const [dataSource, setDataSource] = useState<IDashboardOperation[]>([]);
  //当前文件夹ID
  const [currentParentId, setCurrentParentId] = useState<number>(0);
  //当前编辑的看板
  const [, setCurrentEditBoard] = useState<IDashboardOperation>();
  //新增文件夹modal状态
  const [isFolderAddVisible, setIsFolderAddVisible] = useState<boolean>(false);
  //新增看板modal状态
  const [isBoardAddVisible, setIsBoardAddVisible] = useState<boolean>(false);
  // //看板布局modal状态
  // const [isBoardDesignVisible, setIsBoardDesignVisible] = useState<boolean>(false);
  //新增文件夹LOADING
  const [folderAddLoading, setFolderAddLoading] = useState<boolean>(false);
  //新增看板LOADING
  const [boardAddLoading, setBoardAddLoading] = useState<boolean>(false);
  //文件夹路径
  const [paths, setPaths] = useState<any[]>([{ name: '全部', id: 0 }]);
  //文件夹树状结构
  const [folderTrees, setFolderTrees] = useState<ITreeNode[]>([]);
  //看板搜索值
  const [searchBoardValue, setSearchBoardValue] = useState<string>();
  const [publishFilterValue, setPublishFilterValue] = useState<number>(0);
  const folderAddFormRel: any = createRef();
  const boardAddFormRel: any = createRef();
  const [folderAddForm] = Form.useForm();
  const [boardAddForm] = Form.useForm();
  /**
   * 请求文件夹看板数据
   */
  useEffect(() => {
    setDataSource([])
    dispatch({
      type: 'board/fetchDashboardOperation',
      payload: {  projectId },
    });
  }, [projectId]);

  const buildDatasPath = (datas: IDashboardOperation[]) => {
    const folders: ITreeNode[] = dashboardOperations.filter(d => d.type === 0).map(d => ({
      key: d.id,
      value: d.id,
      title: d.name,
      parent: d.parentId,
    }));
    return datas.map(d => {
      const pathList = getFolderPaths(folders, d.parentId, [], true);
      let path = '';
      if (pathList && pathList.length) {
        path = pathList;
      }
      return { ...d, path };
    });
  };

  const searchFilter = (records: IDashboardOperation[]) => {
    if (!searchBoardValue || searchBoardValue.trim() === '') {
      return records;
    }
    return buildDatasPath(records.filter((v) => !searchBoardValue || searchBoardValue.trim() === '' || (v.name.indexOf(searchBoardValue) !== -1 && v.type === 1)));
  };
  const filterDatasBy = (datas: IDashboardOperation[], filter: any) => {
    const filterKeys: string[] = Object.keys(filter);
    filterKeys.forEach(k => {
      if (filter[k]) {
        datas = datas.filter(d => filter[k](d));
      }
    });
    return datas;
  };
  const publishFilter = (records: IDashboardOperation[]) => {
    if (publishFilterValue === 0) {
      return records;
    }
    const dataFilterSort = (arrs: IDashboardOperation[]) => {
      let datas = arrs;
      datas = filterDatasBy(datas, {
        published: (record: IDashboardOperation) => {
          const v = record.published;
          return publishFilterValue === 0 //0展示所有
            || (
              record.type === 1 &&
              (publishFilterValue === v  //值匹配到的
                || (publishFilterValue === 1 && !v))//未发布状态的看板类型，但是值为null的
            )
            ;
        },
      });
      return datas;
    };
    return buildDatasPath(dataFilterSort(records));
  };
  /**
   * 监听过滤筛选
   */
  useEffect(() => {

    if (publishFilterValue === 0 && (!searchBoardValue || searchBoardValue.trim() === '')) {
      setPathsFolder(currentParentId);
    } else {
      let datas = publishFilter(dashboardOperations);
      datas = searchFilter(datas);
      setPaths([]);
      setDataSource(datas);
    }
  }, [publishFilterValue, searchBoardValue]);

  /**
   * 获取当前Id的路径数组
   * @param data
   * @param id
   * @param paths
   * @param fulled 是否包含当前
   */
  const getFolderPaths: any = (data: ITreeNode[], id: any, paths: any[], fulled?: boolean) => {
    if (!paths) {
      paths = [];
    }
    if (id === 0 && fulled) {
      return [{ id: 0, name: '全部' }, ...paths];
    }
    const currentFolder = data.find(f => f.key === id);
    if (currentFolder) {
      const { key, title, parent } = currentFolder;
      paths = [{ id: key, name: title }, ...paths];
      if (parent === 0) {
        return [{ id: 0, name: '全部' }, ...paths];
      }
      return getFolderPaths(data, parent, paths);
    }
    return paths;
  };
  /**
   * 设置路径
   */
  const setPathsFolder = (id: any) => {
    if (id === 0) {
      setPaths([]);
    } else if (dashboardOperations) {
      // 初始化文件夹树形结构
      const folders: ITreeNode[] = dashboardOperations.filter(d => d.type === 0).map(d => ({
        key: d.id,
        value: d.id,
        title: d.name,
        parent: d.parentId,
      }));
      setPaths(getFolderPaths(folders, id, []));
    }
    dashboardOperations && setDataSource(dashboardOperations.filter(v => v.parentId === id));
  };
  /**
   * 监听当前文件夹ID设置路径
   */
  useEffect(() => {
    setPathsFolder(currentParentId);

  }, [currentParentId]);
  /**
   * 监听接口返回的文件夹看板对象数据并初始化数据
   */
  useEffect(() => {
    if (dashboardOperations && dashboardOperations.length) {
      //初始化表格数据
      setDataSource(dashboardOperations.filter((v) => v.parentId === currentParentId));

      // 初始化文件夹树形结构
      const folders: ITreeNode[] = dashboardOperations.filter(d => d.type === 0).map(d => ({
        key: d.id,
        value: d.id,
        title: d.name,
        parent: d.parentId,
      }));
      const searchFoldersById = (datas: ITreeNode[], pId: any) => {
        const children = datas.filter(v => v.parent === pId);
        if (children) {
          children.map(v => {
            const children1 = searchFoldersById(datas, v.key);
            v.children = children1;
            return v;
          });
        }
        return children;
      };
      const folderTrees = folders.filter((tree: any) => !tree.parent || tree.parent === '').map((root) => {
        root.children = searchFoldersById(folders, root.key);
        return root;
      });
      setFolderTrees([{ key: 0, value: 0, title: '根目录', children: folderTrees }]);
    }
  }, [dashboardOperations]);

  /**
   * 进入文件夹
   * @param val
   */
  const onInto = (val: any) => {
    const { id } = val;
    setCurrentParentId(id);
  };
  /**
   * 文件夹路径的回退
   * @param id
   */
  const onIntoChange = (id: number) => {
    setSearchBoardValue('');
    setPublishFilterValue(0);
    setCurrentParentId(id);
  };
  const leftColums = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (v: any, data: IDashboardOperation) => {
        return (
          <div className={styles.boardName} onClick={() => {
            if (data.type === 0) {
              onInto(data);
            } else if (data.type === 1) {
              intoBoard(data);
            }
          }
          }>
            {data.type === 0 ?
              <FolderFilled style={{ color: '#FFC53D', marginRight: '12px' }} />
              : <FundFilled style={{ color: '#40A9FF', marginRight: '12px' }} />
            }
            {v}
          </div>
        );
      },
    },
    {
      title: '发布状态',
      dataIndex: 'published',
      key: 'published',
      render: (v: any, data: any) => {
        let view: any = '-';
        if (data.published === 1 || (!data.published && data.type === 1)) {
          view = <div className={styles.boardName}>
            <div
              style={{ background: '#ddd', width: '8px', height: '8px', marginRight: '10px', borderRadius: '10px' }} />
            未发布
          </div>;
        } else if (data.published === 2) {
          view = <div className={styles.boardName}>
            <div
              style={{
                background: '#52C41A',
                width: '8px',
                height: '8px',
                marginRight: '10px',
                borderRadius: '10px',
              }} />
            已发布
          </div>;
        }
        return (
          <div className={styles.boardName}>
            {view}
          </div>
        );
      },
    },
  ];
  const intoBoard = (record: IDashboardOperation) => {
    setCurrentEditBoard(record);
    history.push(`/project/${projectId}/portal/${record.dashboardPortalId}/board/${record.id}/design`);
    // handleBoardDesignVisible()
  };
  const rigthColumns = [
    {
      title: '创建者',
      dataIndex: 'creator',
      key: 'creator',
    },
    {
      title: '修改人',
      dataIndex: 'reviser',
      key: 'reviser',
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      sorter: (a: any, b: any) => a.updateTime < b.updateTime ? -1 : 1,
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      render: (v: any, record: IDashboardOperation) => {
        return (
          <div>
            <EditOutlined style={{ marginRight: '12px' }} onClick={() => {
              intoBoard(record);
            }} />
            <DeleteOutlined style={{ marginRight: '12px' }} />
          </div>
        );
      },
    },
  ];
  let columns;
  if ((searchBoardValue && searchBoardValue.trim() !== '') || publishFilterValue !== 0) {
    columns = [
      ...leftColums,
      {
        title: '路径',
        dataIndex: 'path',
        key: 'path',
        render: (value: any) => {
          const pathList: any[] = value ? Array.from(value) : [];
          return <Breadcrumb>
            {
              pathList.map((p: any, idx: number) => {
                const { name, id } = p;
                const isLast = pathList.length === idx + 1;
                let title = <span>{name}</span>;
                if (isLast) {
                  title = name;
                }
                return (
                  <Breadcrumb.Item onClick={() => {
                    onIntoChange(id);
                  }}>
                    {title}
                  </Breadcrumb.Item>
                );
              })
            }

          </Breadcrumb>;
        },
      },
      ...rigthColumns,
    ];
  } else {
    columns = [...leftColums, ...rigthColumns];
  }
  /**
   * 改变新增文件夹弹框modal的状态
   */
  const handleFolderVisible = () => {
    folderAddForm!.resetFields();
    setFolderAddLoading(false);
    setIsFolderAddVisible(!isFolderAddVisible);
  };
  /**
   * 改变新增看板弹框modal的状态
   */
  const handleBoardVisible = () => {
    boardAddForm!.resetFields();
    setBoardAddLoading(false);
    setIsBoardAddVisible(!isBoardAddVisible);
  };

  const mergedColumns = columns.map(col => {
    // if (!col.editable) {
    //   return col;
    // }
    return {
      ...col,
    };
  });

  const onFolderAddSure = async () => {
    try {
      setFolderAddLoading(true);
      const values = await folderAddForm.validateFields();
      const record = {
        id: -1,
        name: values.name,
        creator: currentUser.name,
        reviser: currentUser.name,
        parentId: values.position,
        type: 0,
        config: '',
      };
      dispatch({
        type: 'board/addFolder',
        payload: { projectId, body: record },
        callback: (res: IResponse) => {
          if (res && res.header.code === 200) {
            dispatch({
              type: 'board/fetchDashboardOperation',
              payload: { projectId },
            });
            setCurrentParentId(values.position);
            handleFolderVisible();
          } else {
            message.error('新增文件夹失败');
          }
        },
      });
    } catch (errorInfo) {
      setFolderAddLoading(false);
    }
  };
  const onBoardAddSure = async () => {
    try {
      setBoardAddLoading(true);
      const values = await boardAddForm.validateFields();
      const record = {
        id: -1,
        name: values.name,
        creator: currentUser.name,
        reviser: currentUser.name,
        parentId: values.position,
        type: 1,
        config: '',
      };
      dispatch({
        type: 'board/addFolder',
        payload: { projectId, body: record },
        callback: (res: IResponse) => {
          if (res && res.header.code === 200) {
            dispatch({
              type: 'board/fetchDashboardOperation',
              payload: { projectId },
            });
            setCurrentParentId(values.position);
            handleBoardVisible();
          } else {
            message.error('新增看板失败');
          }
        },
      });
    } catch (errorInfo) {
      setFolderAddLoading(false);
    }
  };
  const searchBoard = (e: any) => {
    const { value } = e.target;
    setSearchBoardValue(value);
  };

  return (
    <div className={styles.board}>
      <div className={styles.boardTitle}>
        <div className={styles.titleName}>看板管理</div>
        <Input
          style={{ width: 240 }}
          placeholder='请输入看板名称或关键字'
          prefix={<SearchOutlined />}
          onChange={searchBoard}
        />
      </div>
      {paths.length > 1 ?
        <Breadcrumb className={styles.paths}>
          {
            paths.map((p: any, idx: number) => {
              const { name, id } = p;
              const isLast = paths.length === idx + 1;
              let title = <span>{name}</span>;
              if (isLast) {
                title = name;
              }
              return (
                <Breadcrumb.Item onClick={!isLast ? () => {
                  // setPaths(paths.filter((p: any, i: number) => i <= idx));
                  onIntoChange(id);
                } : () => {
                }
                }>
                  {title}
                </Breadcrumb.Item>
              );
            })
          }

        </Breadcrumb>
        : null}
      <div className={styles.boardTable}>
        <Modal
          title='新增文件夹'
          visible={isFolderAddVisible}
          destroyOnClose

          onCancel={handleFolderVisible}
          footer={[
            <Button key='back' onClick={handleFolderVisible}>
              取消
            </Button>,
            <Button key='submit' type='primary' loading={folderAddLoading} onClick={onFolderAddSure}>
              确定
            </Button>,
          ]}
        >
          <Form form={folderAddForm} ref={folderAddFormRel} name='control-ref'>
            <Form.Item name='name' label='名称' rules={[{ required: true }]}>
              <Input placeholder='请输入' />
            </Form.Item>
            <Form.Item name='position' label='位置' initialValue={currentParentId} rules={[{ required: true }]}>
              <TreeSelect
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeDefaultExpandAll
                treeData={folderTrees}
              />
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title='新增看板'
          visible={isBoardAddVisible}
          destroyOnClose
          onCancel={handleBoardVisible}
          footer={[
            <Button key='back' onClick={handleBoardVisible}>
              取消
            </Button>,
            <Button key='submit' type='primary' loading={boardAddLoading} onClick={onBoardAddSure}>
              确定
            </Button>,
          ]}
        >
          <Form form={boardAddForm} ref={boardAddFormRel} name='control-ref-2'>
            <Form.Item name='name' label='名称' rules={[{ required: true }]}>
              <Input placeholder='请输入' />
            </Form.Item>
            <Form.Item name='position' label='位置' initialValue={currentParentId} rules={[{ required: true }]}>
              <TreeSelect
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeDefaultExpandAll
                treeData={folderTrees}
              />
            </Form.Item>
          </Form>
        </Modal>
        {/*<ModalNull visible={isBoardDesignVisible}>*/}
        {/*  <BoardDesign onCanel={handleBoardDesignVisible} board={currentEditBoard} />*/}
        {/*</ModalNull>*/}
        <div className={styles.boardHeader}>
          <Select
            value={publishFilterValue}
            style={{ width: 174 }}
            onChange={(e: number) => {
              setPublishFilterValue(e);
            }}
          >
            <Option value={0}>全部</Option>
            <Option value={2}>已发布</Option>
            <Option value={1}>未发布</Option>
          </Select>
          <div className={styles.btns}>
            <div className={classnames({
              [styles.folderAdd]: true,
            })} onClick={handleFolderVisible}>
              <FolderAddOutlined style={{ marginRight: '7px' }} />
              新增文件夹
            </div>
            <div className={styles.dashboardAdd}
                 onClick={handleBoardVisible}
            >
              <FundOutlined style={{ marginRight: '7px' }} />
              新增看板
            </div>
          </div>
        </div>
        <Table
          key={1}
          className={styles.tabel}
          columns={mergedColumns}
          dataSource={dataSource.sort((a: any, b: any) => a.type - b.type)}
          pagination={false}
        />
      </div>
    </div>
  );
};

export default connect(({ board, user }: ConnectState) => ({
  dashboardOperations: board.dashboardOperations,
  currentUser: user.currentUser ? user.currentUser : {},
}))(Board);
